package org.chen.spring.aop.processor;

import net.sf.cglib.proxy.Enhancer;
import org.chen.spring.aop.factory.AspectFactory;
import org.chen.spring.core.processor.BeanPostProcessor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * AOP后处理器
 *
 * @author Chen
 * @since 2023/6/8 16:15
 */

public class ChenAopBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {

        boolean hasAop = false;
        //获取所有切面
        ConcurrentHashMap<Annotation, Map<String, Method>> aspectMap = AspectFactory.getAspectMap();
        //过滤是否存在AOP
        Collection<Map<String, Method>> values = aspectMap.values();
        for (Method method : bean.getClass().getDeclaredMethods()) {
            for (Annotation declaredAnnotation : method.getDeclaredAnnotations()) {
                for (Map<String, Method> value : values) {
                    if (value.containsKey(declaredAnnotation.annotationType().getSimpleName())) {
                        hasAop = true;
                        break;
                    }
                }
            }

        }
        //如果是则返回代理对象
        if (hasAop) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(bean.getClass());
            enhancer.setCallback(new AopInterceptor());
            bean = enhancer.create();
        }
        return bean;
    }
}
